package com.onpositive.funkytable.swt;

import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.graphics.TextLayout;
import org.eclipse.swt.graphics.TextStyle;
import org.eclipse.swt.widgets.Display;

import com.onpositive.funkytable.IFunkyStyle;
import com.onpositive.funkytable.IFunkyTextControl;
import com.onpositive.funkytable.Point;

public class FunkyText implements IFunkyTextControl, ISWTControl {

	String text = "";
	private int align;
	private FunkyStyle style;

	@Override
	public void setText(CharSequence value) {
		this.text = value.toString();
	}

	@Override
	public void setGravity(int gravity) {
		this.align = gravity;
	}

	@Override
	public Point measure(int desiredwidth, int desiredheight) {
		TextLayout ll = createLayout(desiredwidth);
		Rectangle bounds = ll.getBounds();
		ll.dispose();
		return new Point(bounds.width, bounds.height);
	}

	protected TextLayout createLayout(int desiredwidth) {
		TextLayout ll = new TextLayout(Display.getCurrent());
		ll.setText(text);
		if (desiredwidth!=-1){
			ll.setWidth(desiredwidth);
		}
		if (align == IFunkyTextControl.LEFT) {
			ll.setAlignment(SWT.LEFT);
		}
		if (align == IFunkyTextControl.RIGHT) {
			ll.setAlignment(SWT.RIGHT);
		}
		if (align == IFunkyTextControl.CENTER) {
			ll.setAlignment(SWT.CENTER);
		}
		if (style != null) {
			TextStyle textStyle = new TextStyle(null, style.fgcolor,
					style.bgcolor);
			ll.setStyle(textStyle, 0, text.length());
		}
		return ll;
	}

	@Override
	public void setStyle(IFunkyStyle style) {
		this.style = (FunkyStyle) style;
	}

	@Override
	public IFunkyStyle getStyle() {
		return style;
	}

	@Override
	public void draw(GC gc, int x, int y, int width, int height) {
		TextLayout createLayout = createLayout(width);
		gc.setClipping(x, y, width, height);
		if (style!=null){
			gc.setBackground(style.bgcolor);
			gc.setForeground(style.fgcolor);			
		}
		gc.fillRectangle(x, y, width, height);
		createLayout.draw(gc, x, y);
		createLayout.dispose();
	}

	@Override
	public void layout(int width) {
		
	}
}
